const { ccclass, property } = cc._decorator;

enum MoveDirection {
    UpDown,
    LeftRight,
}

enum Direction {
    Up,
    Down,
    Left,
    Right
}

const BLOCK_MARGIN = 1

@ccclass
export default class ZhuanBlock extends cc.Component {


    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = '0';

    private originalPos: cc.Vec3 = null; // 方块的初始位置

    private blockStartPos: cc.Vec2 = null; // 方块开始位置

    isLockDirection = false // 是否已经锁定了移动方向

    // LIFE-CYCLE CALLBACKS:
    private movingDirection = MoveDirection.LeftRight;

    row = 0; // 方块所在行

    column = 0; // 方块所在列

    MainGame = null;

    movingBlocks = []

    init(row, column){
        this.row = row;
        this.column = column
        this.MainGame = window.MainGame
    }
    onDestroy() {
        this.MainGame = null
    }
    onLoad() {
        this.text = 1 + Math.floor(Math.random() * 9) + ''
        this.label.string = this.text

        
    }
    start() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this)
    }
    onTouchStart(event: cc.Event.EventTouch) {
        // 记录触摸起始位置
        let touchPos = event.getLocation();
        // 记录原始位置
        this.originalPos = this.node.position;
        this.blockStartPos = this.node.convertToNodeSpaceAR(touchPos);
    }
    onTouchMove(event: cc.Event.EventTouch) {
        // 记录触摸结束位置
        let touchPos = event.getLocation();
        let touchMovePos = this.node.convertToNodeSpaceAR(touchPos);
        // 计算触摸偏移，只能竖向移动或者横向移动
        let delta = touchMovePos.sub(this.blockStartPos);
        if(!this.isLockDirection){
            // 确定移动方向
            if (Math.abs(delta.x) > Math.abs(delta.y)) {
                // 横向移动
                this.movingDirection = MoveDirection.LeftRight
            } else {
                // 竖向移动
                this.movingDirection = MoveDirection.UpDown
            }
            this.isLockDirection = true;
        }
        
        if (this.isValidMove(touchMovePos, delta)) {
            let blocks = this.getValidMoveBlock(touchMovePos, delta)
            blocks.unshift(this.node);
            this.movingBlocks = blocks
            if (this.movingDirection === MoveDirection.LeftRight) {
                let lastBlock = blocks[blocks.length - 1]
                let lastBlockRightBorder = lastBlock.width / 2 + lastBlock.x + BLOCK_MARGIN;
                let lastBlockLeftBorder = lastBlock.x - lastBlock.width / 2 - BLOCK_MARGIN;
                let lastColunm = lastBlock.getComponent(ZhuanBlock).column
                if(delta.x > 0){
                    let rightBlock = this.getLastBlockFromRight(lastColunm)
                    // 右边是否还有方块
                    if(rightBlock){
                        let rightBlockLeftBorder = rightBlock.x - rightBlock.width / 2 - BLOCK_MARGIN;
                        if(lastBlockRightBorder >= rightBlockLeftBorder){
                            return
                        }
                    }else{
                        // 到了右边界，停止移动
                        if(lastBlockRightBorder >= this.MainGame.itemLayout.width / 2){
                            return
                        }
                    }
                }else{
                    let leftBlock = this.getLastBlockFromLeft(lastColunm)
                    if(leftBlock){
                        let leftBlockRightBorder = leftBlock.width / 2 + leftBlock.x + BLOCK_MARGIN;
                        if(lastBlockLeftBorder <= leftBlockRightBorder){
                            return
                        }
                    }else{
                        // 到了左边界，停止移动
                        if(lastBlockRightBorder <= -this.MainGame.itemLayout.width / 2){
                            return
                        }
                    }
                }
                // 横向移动
                blocks.forEach(block => {
                    block.x += delta.x;
                })
            } else {
                // 竖向移动
                blocks.forEach(block => {
                    block.y += delta.y;
                })
            }
            // this.node.setPosition(touchMovePos)
        }
    }
    onTouchEnd(event: cc.Event.EventTouch) {
        this.isLockDirection = false;
        // 记录触摸结束位置
        let touchPos = event.getLocation();
        let touchEndPos = this.node.convertToNodeSpaceAR(touchPos);
        // 计算触摸偏移，只能竖向移动或者横向移动
        let delta = touchEndPos.sub(this.blockStartPos);
        let canMatchResult = this.checkMatch()
        if (!canMatchResult) {
            // 无法消除，将方块移回原始位置
            this.rollback();
        }else{
            this.MainGame.blocks[this.row][this.column] = null
            let block = canMatchResult.getComponent(ZhuanBlock)
            this.MainGame.blocks[block.row][block.column] = null
            canMatchResult.destroy()
            canMatchResult = null;
            this.node.destroy()
        }
    }
    // 没有消除，则回归原来的地方
    rollback(){
        if (this.movingDirection === MoveDirection.LeftRight) {
            this.node.setPosition(this.originalPos);
            this.movingBlocks.shift()
            console.log(this.movingBlocks.length)
            while(this.movingBlocks.length){
                let block = this.movingBlocks.shift()
                let i = 1;
                if(block.getComponent(ZhuanBlock).column > this.column){
                    block.x = this.originalPos.x + i * this.node.width;
                }else{
                    block.x = this.originalPos.x - i * this.node.width;
                }
                i++
            }
        }else{

        }
    }
    // 右侧是否含有方块阻挡
    getLastBlockFromRight(column){
        for(let i = column + 1; i < this.MainGame.column; i++){
            let block = this.MainGame.blocks[this.row][i]
            if(block !== null){
                return block
            }
        }
        return false
    }
    // 左侧是否含有方块阻挡
    getLastBlockFromLeft(column){
        for(let i = column - 1; i >= 0; i--){
            let block = this.MainGame.blocks[this.row][i]
            if(block !== null){
                return block
            }
        }
        return false
    }
    getLastBlockFromTop(){
        for(let i = 0; i < this.MainGame.row ; i++){
            if(this.MainGame.blocks[i][this.column] === null){
                return this.MainGame.blocks[i - 1][this.column]
            }
        }
        return false
    }
    getLastBlockFromDown(){
        for(let i = this.MainGame.row - 1; i >= 0 ;i--){
            if(this.MainGame.blocks[i][this.column] === null){
                return this.MainGame.blocks[i + 1][this.column]
            }
        }
        return false
    }


    isValidMove(pos: cc.Vec2, delta): boolean {
        // 是否有空位移动
        if(this.movingDirection === MoveDirection.LeftRight){
            // 右边移动
            if(delta.x > 0){
                for(let i = this.column + 1; i < this.MainGame.column; i++){
                    if(this.MainGame.blocks[this.row][i] === null){
                        return true
                    }
                }
                return false
            }else{
                for(let i = this.column - 1; i >= 0; i--){
                    if(this.MainGame.blocks[this.row][i] === null){
                        return true
                    }
                }
                return false
            }
        }else{
            if(delta.y > 0){
                for(let i = this.row - 1; i >= 0; i--){
                    if(this.MainGame.blocks[i][this.column] === null){
                        return true
                    }
                }
                return false
            }else{
                for(let i = this.row + 1; i < this.MainGame.row; i++){
                    if(this.MainGame.blocks[i][this.column] === null){
                        return true
                    }
                }
                return false
            }
        }
    }
    // 获取可以同时推动的方块
    getValidMoveBlock(pos: cc.Vec2, delta) {
        let blocks = []
        if(this.movingDirection === MoveDirection.LeftRight){
            // 右边移动
            if(delta.x > 0){
                for(let i = this.column + 1; i < this.MainGame.column; i++){
                    let block = this.MainGame.blocks[this.row][i]
                    if(block){
                        blocks.push(block)
                    } else{
                        return blocks;
                    }
                }
            }else{
                for(let i = this.column - 1; i >= 0; i--){
                    let block = this.MainGame.blocks[this.row][i]
                    if(block){
                        blocks.push(block)
                    } else{
                        return blocks;
                    }
                }
            }
        }else{
            if(delta.y > 0){
                for(let i = this.row - 1; i >= 0; i--){
                    let block = this.MainGame.blocks[i][this.column]
                    if(block){
                        blocks.push(block)
                    } else{
                        return blocks;
                    }
                }
            }else{
                for(let i = this.row + 1; i < this.MainGame.row; i++){
                    let block = this.MainGame.blocks[i][this.column]
                    if(block){
                        blocks.push(block)
                    } else{
                        return blocks;
                    }
                }
            }
        }
        return blocks;
    }

    checkMatch() {
        // 向四个方向遍历，最近的一个方块，如果类型一致则可以消除
        for(let i = this.column + 1; i < this.MainGame.column; i++){
            let block = this.MainGame.blocks[this.row][i]
            if(block){
                if(this.canMatch(block)){
                    return block;
                }else{
                    break;
                }
            }
        }
        for(let i = this.column - 1; i >= 0; i--){
            let block = this.MainGame.blocks[this.row][i]
            if(block){
                if(this.canMatch(block)){
                    return block;
                }else{
                    break;
                }
            }
        }
        for(let i = this.row - 1; i >= 0; i--){
            let block = this.MainGame.blocks[i][this.column]
            if(block){
                if(this.canMatch(block)){
                    return block;
                }else{
                    break;
                }
            }
        }
        for(let i = this.row + 1; i < this.MainGame.row; i++){
            let block = this.MainGame.blocks[i][this.column]
            if(block){
                if(this.canMatch(block)){
                    return block;
                }else{
                    break;
                }
            }
        }
        return false; 
    }
    // 是否能够match
    canMatch(block){
        if(block.getComponent(ZhuanBlock).text === this.text){
            return true
        }
        return false
    }

    // update (dt) {}
}
